class CustomerController < ApplicationController

  before_filter :authenticate
  
  def index
    @customers = Customer.find(:all, :order => "name")
  end
  
  def list
    @customers = Customer.find(:all, :order => "name")
    render :update do |page|
      page.replace_html "customer_list" , :partial => 'list'
      page.show "customer_list"
      if params[:displayform] == 'none'
        page.hide "customer_form"
      end
    end
  end
  
  def list_classification
    @classifications = Classification.find(:all, :conditions => ["classification_id = (?)", params[:id] ] ,:order => "name ASC")
    render :update do |page|
      if @classifications.length > 0
        page.replace_html "classification_#{params[:id]}" , :partial => 'list_classification'
      else
        page.replace_html "classification_#{params[:id]}" , "<ul><li>Não existe classificações associadas.</li></ul>"
      end
    end
  end
  
  def alter
    @customer = Customer.find(params[:customer][:id])
    if request.post?
      @customer.attributes = params[:customer]
      @customer.classification_ids = params[:classification_ids].split(',')
      if @customer.save
        redirect_to :action => "list", :displayform => "none"
      end
    end
  end

  def create
    @customer = Customer.new
    if request.post?
      @customer.attributes = params[:customer]
      @customer.classification_ids = params[:classification_ids].split(',')
      if @customer.save
        redirect_to :action => "list", :displayform => "none"
      end
    end
  end

  def remove
    if params[:id]
      @customer = Customer.find(params[:id])
      if @customer.destroy
        redirect_to :action => "list", :displayform => "none"
      end
    end
  end
  
  def form

    @classifications = Classification.find(:all, :conditions => "classification_id is null" ,:order => "name ASC")

    if params[:id]
      @customer = Customer.find(params[:id])
    else
      @customer = Customer.new
    end

    render :update do |page|
      page.replace_html "customer_form" , :partial => 'form'
      page.show "customer_form"
      
      for classification in @customer.classifications
        page << "Customer.addClassification('#{classification[:id]}','#{classification[:name]}')"
      end
      
    end

  end
  
  protected
  
=begin
Filtro de autenticação do controler
=end
  def authenticate
    authenticate_check('(ADM:ALL||CSTM:VIEW||CSTM:ALL)','/')
  end
  
end
